package com.chookss.home.publish;


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.sdk.android.vod.upload.VODSVideoUploadCallback;
import com.alibaba.sdk.android.vod.upload.VODSVideoUploadClient;
import com.alibaba.sdk.android.vod.upload.VODSVideoUploadClientImpl;
import com.alibaba.sdk.android.vod.upload.model.SvideoInfo;
import com.alibaba.sdk.android.vod.upload.session.VodHttpClientConfig;
import com.alibaba.sdk.android.vod.upload.session.VodSessionCreateInfo;
import com.chookss.BuildConfig;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.base.Token;
import com.chookss.home.entity.LogEntity;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.lzy.okgo.model.Response;
import com.vincent.videocompressor.VideoCompress;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class UploadLogService extends Service {
    //    private VODUploadClient uploader;
    private String secretToken;
    private String expireTime = "60000";
    private VODSVideoUploadClient vodsVideoUploadClient;
    private VodHttpClientConfig vodHttpClientConfig;
    public static int NotificationId = 1;
    private ArrayList<LogEntity.VideoBean> picList = new ArrayList<>();
    private ArrayList<LogEntity.VideoBean> videoList = new ArrayList<>();
    private ArrayList<LogEntity.DocunmentBean> docunmentList = new ArrayList<>();
    private int picNum = 0, videoNum = 0, docunmentNum = 0;
    private ArrayList<LogEntity> allList = new ArrayList<>();
    //专门设置这两个值以防止多个日志同时上传  第一个上传完立即上传，然后每次上传的都是列表最新的一个
    private ArrayList<Integer> statusList = new ArrayList<>();
    private boolean beginUpload=false;//上传中不得重新开始
    private boolean stopUpload=false;//默认正常上传  当true时切换账号中止上传
    private String compressFileUrl;  //视频压缩后的文件地址
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //初始化短视频上传对象
        MyApp.uploadLogStatus=true;
        EventBus.getDefault().register(this);
        vodsVideoUploadClient = new VODSVideoUploadClientImpl(this.getApplicationContext());
        vodsVideoUploadClient.init();
        //构建上传参数
//参数请确保存在，如不存在SDK内部将会直接将错误throw Exception
//文件路径保证存在之外因为Android 6.0之后需要动态获取权限，请开发者自行实现获取"文件读写权限"
        vodHttpClientConfig = new VodHttpClientConfig.Builder()
                .setMaxRetryCount(2)//重试次数
                .setConnectionTimeout(15 * 1000)//连接超时
                .setSocketTimeout(15 * 1000)//socket超时
                .build();
        secretToken = Token.INSTANCE.getToken();
        registerBoradcastReceiver();
        initNotification();
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        LogEntity newLogEntity = (LogEntity) intent.getSerializableExtra("logEntity");
        int newCacheStatus = intent.getIntExtra("cacheStatus", 0);
        if (newLogEntity != null) {
            allList.add(newLogEntity);
            statusList.add(newCacheStatus);
            dealCacheData(newCacheStatus,newLogEntity);
            setNewLogData();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void setNewLogData() {
        if(!beginUpload){
            beginUpload=true;
            allList.get(0).getPictureList().clear();
            videoList.clear();
            picList.clear();
            docunmentList.clear();
            picNum=0;
            videoNum=0;
            docunmentNum=0;
            for (int i = 0; i < allList.get(0).getVideoBeanlist().size(); i++) {
                if (allList.get(0).getVideoBeanlist().get(i).getType().equals("1")) {
                    videoList.add(allList.get(0).getVideoBeanlist().get(i));
                } else {
                    picList.add(allList.get(0).getVideoBeanlist().get(i));
                    allList.get(0).getPictureList().add(allList.get(0).getVideoBeanlist().get(i).getUrl());
                }
            }
            docunmentList.addAll(allList.get(0).getDocunmentBeanlist());
            if (picList.size() == 0) {
                if (docunmentList.size() == 0) {
                    if (videoList.size() == 0) {
                        uploadData();
                    } else {
                        uploadVideo();
                    }
                } else {
                    uploadDocunment();
                }
            } else {
                uploadPic();
            }
        }
    }

    private void uploadPic() {
        if (picList.get(picNum).getUrl().startsWith("http")) {
            picNum++;
            if (picNum >= picList.size()) {
                if (docunmentList.size() == 0) {
                    if (videoList.size() == 0) {
                        uploadData();
                    } else {
                        uploadVideo();
                    }
                } else {
                    uploadDocunment();
                }
            } else {
                uploadPic();
            }
        } else {
            MyHttpRequest.uploadPicture(Urls.uploadPicture, this, "4", new File(picList.get(picNum).getUrl()), new JsonCallback<String>() {
                @Override
                public void onSuccess(Response<String> response) {
                    JSONObject result = null;
                    JSONObject data = null;
                    if(stopUpload){
                        dealCacheData(2,null);
                        stopSelf();
                        return;
                    }
                    try {
                        result = new JSONObject(response.body().toString());
                        if (result.getString("code").equals("200")) {
                            data = result.getJSONObject("data");
                            Message msg = handler.obtainMessage();
                            msg.arg1 = (picNum * 100) / (picList.size() + videoList.size() + docunmentList.size());
                            handler.sendMessage(msg);
                            picList.get(picNum).setUrl(data.getString("originalUrl"));
                            picNum++;
                            if (picNum >= picList.size()) {
                                if (docunmentList.size() == 0) {
                                    if (videoList.size() == 0) {
                                        uploadData();
                                    } else {
                                        uploadVideo();
                                    }
                                } else {
                                    uploadDocunment();
                                }
                            } else {
                                uploadPic();
                            }
                        } else {
                            dealCacheData(2,null);
                            if (result.getString("code").startsWith("400")) {
                                OkGoUtil.onErrorIntent(result.getString("code"),result.getString("msg"));
                            }else{
                                MyToast.show("图片上传失败，请稍后重试");
                            }
                            stopSelf();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        dealCacheData(2,null);
                        MyToast.show("图片上传失败，请稍后重试");
                        stopSelf();
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    dealCacheData(2,null);
                    MyToast.show("图片上传失败，请稍后重试");
                    stopSelf();
                }
            });
        }
    }

    private void uploadDocunment() {
        if (!Utils.isNull(docunmentList.get(docunmentNum).getDataCode())) {
            docunmentNum++;
            if (docunmentNum >= docunmentList.size()) {
                if (videoList.size() == 0) {
                    uploadData();
                } else {
                    uploadVideo();
                }
            } else {
                uploadDocunment();
            }
        } else {
            MyHttpRequest.uploadDataFileNew(Urls.uploadDataFile, this, new File(docunmentList.get(docunmentNum).getDataPath()), new JsonCallback<String>() {
                @Override
                public void onSuccess(Response<String> response) {
                    JSONObject result = null;
                    try {
                        if(stopUpload){
                            dealCacheData(2,null);
                            stopSelf();
                            return;
                        }
                        result = new JSONObject(response.body().toString());
                        if (result.getString("code").equals("200")) {
                            Message msg = handler.obtainMessage();
                            msg.arg1 = ((picNum + docunmentNum) * 100) / (picList.size() + videoList.size() + docunmentList.size());
                            handler.sendMessage(msg);
                            docunmentList.get(docunmentNum).setDataCode(result.getString("data"));
                            docunmentNum++;
                            if (docunmentNum >= docunmentList.size()) {
                                if (videoList.size() == 0) {
                                    uploadData();
                                } else {
                                    uploadVideo();
                                }
                            } else {
                                uploadDocunment();
                            }
                        } else {
                            dealCacheData(2,null);
                            if (result.getString("code").startsWith("400")) {
                                OkGoUtil.onErrorIntent(result.getString("code"),result.getString("msg"));
                            }else{
                                MyToast.show("资料上传失败，请稍后重试");
                            }
                            stopSelf();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        dealCacheData(2,null);
                        MyToast.show("资料上传失败，请稍后重试");
                        stopSelf();
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    dealCacheData(2,null);
                    MyToast.show("资料上传失败，请稍后重试");
                    stopSelf();
                }
            });
        }
    }

    private void uploadVideo() {
        if (!Utils.isNull(videoList.get(videoNum).getVideoId())) {
            videoNum++;
            if (videoNum >= videoList.size()) {
                uploadData();
            } else {
                uploadVideo();
            }

        } else {
            //压缩代码放后台执行
            String fileUrl=videoList.get(videoNum).getUrl();
            String vedioType = fileUrl.substring(fileUrl.lastIndexOf(".") + 1, fileUrl.length());
            compressFileUrl = getExternalFilesDir(Urls.UPLOADVIDEO).getAbsolutePath() + File.separator + System.currentTimeMillis() + "." + vedioType;
            Uri vedioUri = null;
            File vedio = new File(fileUrl);
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                vedioUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileProvider", vedio);
            } else {
                vedioUri = Uri.fromFile(vedio);
            }
            int level = 3;
            int size = FileUtilss.getFileSize(vedio);
            int time = FileUtilss.getVideoTime(this, vedioUri);
            if (size <= 51200) {
                videoList.get(videoNum).setVideocompress(fileUrl);
                dealVideo(false);
            } else {
                if (time <= 30) {
                    videoList.get(videoNum).setVideocompress(fileUrl);
                    dealVideo(false);
                } else {
                    float compare = size / time;
                    if (compare <= 2500) {
                        level = 2;
                    } else {
                        level = 3;
                    }
                    VideoCompress.compressVideo(fileUrl, compressFileUrl, level, new VideoCompress.CompressListener() {
                        @Override
                        public void onStart() {
                        }
                        @Override
                        public void onSuccess() {
                            //压缩成功则开始上传视频
                            videoList.get(videoNum).setVideocompress(compressFileUrl);
                            dealVideo(true);
                        }

                        @Override
                        public void onFail() {
                            dealCacheData(2,null);
                            MyToast.show("视频发布失败，请稍后重试");
                        }

                        @Override
                        public void onProgress(float percent) {
                            int progress = (int) (percent)/2;
                            Message msg = handler.obtainMessage();
                            msg.arg1 = ((picNum + docunmentNum + videoNum) * 100 + progress) / (picList.size() + videoList.size() + docunmentList.size());
                            handler.sendMessage(msg);
                        }
                    });
                }
            }
        }
    }
    private void dealVideo(boolean isCompress) {
        //构建短视频VideoInfo，常见的描述、标题、详情都可以设置
        SvideoInfo svideoInfo = new SvideoInfo();
        svideoInfo.setTitle(videoList.get(videoNum).getVideoTitle());//标题
        svideoInfo.setDesc("");//文件详情
        svideoInfo.setCateId(1);//分类ID
        //构建点播上传参数（重要）
        VodSessionCreateInfo vodSessionCreateInfo = new VodSessionCreateInfo.Builder()
                .setImagePath(videoList.get(videoNum).getVideoCoverPath())//图片地址
                .setVideoPath(videoList.get(videoNum).getVideocompress())//视频地址
                .setAccessKeyId(MyApp.accessKeyId)//临时accessKeyId
                .setAccessKeySecret(MyApp.accessKeySecret)//临时accessKeySecret
                .setSecurityToken(secretToken)//securityToken
                .setExpriedTime(expireTime)//STStoken过期时间
//                .setRequestID(requestId)//requestID，开发者可以传将获取STS返回的requestID设置也可以不设
                .setIsTranscode(true)//是否转码，如开启转码请AppSever务必监听服务端转码成功的通知
                .setSvideoInfo(svideoInfo)//短视频信息
                .setVodHttpClientConfig(vodHttpClientConfig)//网络参数
                .build();
        vodsVideoUploadClient.uploadWithVideoAndImg(vodSessionCreateInfo, new VODSVideoUploadCallback() {
            @Override
            public void onUploadSucceed(String videoId, String imageUrl) {
                //上传成功返回视频ID和图片URL
                KLog.i("onUploadSucceed" + "videoId:" + videoId + "imageUrl" + imageUrl);

                videoList.get(videoNum).setVideoId(videoId);
                videoList.get(videoNum).setVideoCoverPath(imageUrl);
                videoNum++;
                Message msg = handler.obtainMessage();
                msg.arg1 = ((picNum + docunmentNum + videoNum) * 100) / (picList.size() + videoList.size() + docunmentList.size());
                handler.sendMessage(msg);
                if(stopUpload){
                    dealCacheData(2,null);
                    stopSelf();
                }else{
                    if (videoNum >= videoList.size()) {
                        uploadData();
                    } else {
                        uploadVideo();
                    }
                }

            }

            @Override
            public void onUploadFailed(String code, String message) {
                //上传失败返回错误码和message，错误码有详细的错误信息请开发者仔细阅读
                KLog.i("onUploadFailed" + "code" + code + "message" + message);
                dealCacheData(2,null);
                MyToast.show("视频发布失败，请稍后重试");
                stopSelf();
            }

            @Override
            public void onUploadProgress(long uploadedSize, long totalSize) {
                //上传的进度回调，非UI线程
                if(stopUpload){
                    dealCacheData(2,null);
                    stopSelf();
                }else {
                    int progress = (int) (uploadedSize * 100 / totalSize);
                    KLog.i("onUploadProgress" + progress + "%");
                    Message msg = handler.obtainMessage();
                    if(isCompress){
                        msg.arg1 = ((picNum + docunmentNum + videoNum) * 100 +50+ progress/2) / (picList.size() + videoList.size() + docunmentList.size());
                    }else {
                        msg.arg1 = ((picNum + docunmentNum + videoNum) * 100 + progress) / (picList.size() + videoList.size() + docunmentList.size());
                    }
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onSTSTokenExpried() {
                KLog.i("onSTSTokenExpried");
                //STS token过期之后刷新STStoken，如正在上传将会断点续传
//                vodsVideoUploadClient.refreshSTSToken(accessKeyId,accessKeySecret,secretToken,expireTime);
            }

            @Override
            public void onUploadRetry(String code, String message) {
                //上传重试的提醒
                KLog.i("onUploadRetry" + "code" + code + "message" + message);
            }

            @Override
            public void onUploadRetryResume() {
                //上传重试成功的回调，告知用户重试成功
                KLog.i("onUploadRetryResume");
            }
        });

    }

    private void uploadData() {
        Map<String, String> map = new HashMap<>();
        String pictureUrl = "", fileUrl = "", videoIds = "", videoCoverPath = "";
        for (int i = 0; i < picList.size(); i++) {
            if (i != 0) {
                pictureUrl = pictureUrl + "," + picList.get(i).getUrl();
            } else {
                pictureUrl = pictureUrl + picList.get(i).getUrl();
            }
        }
        for (int i = 0; i < docunmentList.size(); i++) {
            if (i != 0) {
                fileUrl = fileUrl + "," + docunmentList.get(i).getDataCode();
            } else {
                fileUrl = fileUrl + docunmentList.get(i).getDataCode();
            }
        }
        for (int i = 0; i < videoList.size(); i++) {
            if (i != 0) {
                videoIds = videoIds + "," + videoList.get(i).getVideoId();
                videoCoverPath = videoCoverPath + "," + videoList.get(i).getVideoCoverPath();
            } else {
                videoIds = videoIds + videoList.get(i).getVideoId();
                videoCoverPath = videoCoverPath + videoList.get(i).getVideoCoverPath();
            }
        }
        map.put("pictureUrl", pictureUrl);
        map.put("fileUrl", fileUrl);
        map.put("videoId", videoIds);
        map.put("videoCoverPath", videoCoverPath);
        String url = "";
        if (allList.get(0).getReportType().equals("3")) {
            map.put("title", allList.get(0).getTitle());
            map.put("content", allList.get(0).getContent());
            url = Urls.saveDiary;
        } else {
            url = Urls.saveReportCommon;
            map.put("reportType", allList.get(0).getReportType());
            map.put("finishWork", allList.get(0).getFinishWork());
            map.put("unFinishWork", allList.get(0).getUnFinishWork());
            map.put("nextWorkPlan", allList.get(0).getNextWorkPlan());
            map.put("needHelpWork", allList.get(0).getNeedHelpWork());
            map.put("remark", allList.get(0).getRemark());
        }
        if (allList.get(0).isModify()) {
            map.put("reportCode", allList.get(0).getReportCode());
            if (allList.get(0).getReportType().equals("3")) {
                url = Urls.updateDiary;
            } else {
                url = Urls.updateReportCommon;
            }
        }
        map.put("sort", allList.get(0).getSort());
        map.put("teamCode", allList.get(0).getTeamCode());
        if (stopUpload) {
            dealCacheData(2,null);
            stopSelf();
        }
        MyHttpRequest.postRequest(url, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        dealCacheData(1,allList.get(0));
                        for (int i = 0; i < picList.size(); i++) {
                            FileUtilss.delFile(picList.get(i).getLocUrl());
                        }
                        for (int i = 0; i < videoList.size(); i++) {
                            FileUtilss.delFile(videoList.get(i).getVideocompress());
                            if(!videoList.get(i).getUrl().equals(videoList.get(i).getVideocompress())){
                                FileUtilss.delFile(videoList.get(i).getUrl());
                            }
                            FileUtilss.delFile(videoList.get(i).getVideoCoverPath());
                            FileUtilss.delFile(videoList.get(i).getVideoLocCoverPath());
                        }
                        if(allList.size()>1){
                            allList.remove(0);
                            beginUpload=false;
                            setNewLogData();
                        }else{
                            if (allList.get(0).isModify()) {
                                MyToast.show("修改成功");
                            } else {
                                MyToast.show("发布成功");
                            }
                            EventBus.getDefault().post(new MyEvent("RefreshLogFragment"));
                            stopSelf();
                        }
                    } else {
                        dealCacheData(2,null);
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                        stopSelf();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dealCacheData(2,null);
                    if (allList.get(0).isModify()) {
                        MyToast.show("修改失败，请稍后重试");
                    } else {
                        MyToast.show("发布失败，请稍后重试");
                    }
                    stopSelf();
                }

            }
        });
    }


    private NotificationManager mNManager;
    private Notification notification;

    private void initNotification() {
        //获得通知消息管理类对象
        mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Bitmap largeBitmap = GlideUtils.loadLogo(this);
        notification = new Notification(GlideUtils.loadLogoId(this), "带进条的提醒", System.currentTimeMillis());
//Android8.0以上必须添加 渠道 才能显示通知栏
        RemoteViews contentView = new RemoteViews(getApplication().getPackageName(), R.layout.vedio_upload);
        contentView.setProgressBar(R.id.progressbarUpload, 100, 0, false);
        contentView.setTextViewText(R.id.tvProcess, "已上传" + "0%");
        contentView.setImageViewResource(R.id.appdown_ivLogo, GlideUtils.loadLogoId(this));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //创建渠道
            String id = "vedio_upload_channel";
            String name = getResources().getString(R.string.app_name);
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
            mNManager.createNotificationChannel(mChannel);
            //设置图片,通知标题,发送时间,提示方式等属性
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, id);
            int PROGRESS_MAX = 100;
            int PROGRESS_CURRENT = 0;
            builder.setCustomContentView(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false)
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
//            startForeground(1, notification);

        } else {
            //设置图片,通知标题,发送时间,提示方式等属性
            Notification.Builder builder = new Notification.Builder(this);
            builder.setContent(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
        }
        mNManager.notify(NotificationId, notification);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            notification.contentView.setProgressBar(R.id.progressbarUpload, 100, msg.arg1,
                    false);
            notification.contentView.setTextViewText(R.id.tvProcess, "已上传"
                    + msg.arg1 + "%");
            mNManager.notify(NotificationId, notification);
            if (msg.arg1 == 100) {
                mNManager.cancel(NotificationId);
            }
            super.handleMessage(msg);
        }
    };

    private void dealCacheData(int type,LogEntity data) {
        //0开始上传缓存本地备份1成功 2失败3重新上传
        if(type==2){
            for (int i = 0; i <allList.size() ; i++) {
                XJson.setLogCache(this, type, allList.get(i));
            }
        }else{
            XJson.setLogCache(this, type, data);
        }

    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (context != null && intent != null && intent.getAction() != null) {

                if (action.equals(StaticClass.ACCOUNT_OUT)) {
                    //账号退出所有 上传数据全部当做失败处理
                    dealCacheData(2,null);
                    stopSelf();
                }
            }
        }

    };
    private boolean registTag = false;//判断重复注册

    private void registerBoradcastReceiver() {
        if (mBroadcastReceiver != null) {
            IntentFilter myIntentFilter = new IntentFilter();
            myIntentFilter.addAction(StaticClass.ACCOUNT_OUT);// 关闭
            //注册广播
            LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
            registTag = true;
        }

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("Stop_File_Upload")) {
               //中止上传任务
                stopUpload=true;
                MyApp.uploadRecordStatus=false;
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        MyApp.uploadLogStatus=false;
        EventBus.getDefault().unregister(this);
        if (vodsVideoUploadClient != null) {
            vodsVideoUploadClient.cancel();
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
        if (mNManager != null) {
            mNManager.cancel(NotificationId);
        }
    }
}